package com.hlkj.baojin.dao.repository;

import com.hlkj.baojin.constant.BaseRepository;
import com.hlkj.baojin.constant.BaojinConstant;
import com.hlkj.baojin.entity.Company;
import com.hlkj.baojin.entity.dto.CompanySearchDto;
import com.hlkj.baojin.entity.dto.ModelList;
import com.hlkj.baojin.utils.PatternUtil;
import com.hlkj.baojin.utils.bean.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author HULIN
 * @created with: baojin
 * @package com.hlkj.baojin.dao.repository
 * @description:
 * @date 2018/12/17 12:42
 * @modified By:
 * @Copyright © 2018 HAILIANG Info. Tech Ltd. All rights reserved.
 */
@Component
public class CompanyRepository extends BaseRepository<Company> {

    public CompanyRepository(MongoTemplate mongoTemplate) {
        super(mongoTemplate);
    }

    public void updateCompanyNotNull(Company company) {
        Company companyDB = new Company();
        companyDB.setId(company.getId());
        super.updateByBean(companyDB, company);
    }

    public ModelList<Company> getCompany(CompanySearchDto companySearchDto) {
        Query query = new Query();

        if(StringUtils.isNotBlank(companySearchDto.getMultiCondition())) {
            Pattern pattern = PatternUtil.fuzzyMatch(companySearchDto.getMultiCondition());
            query.addCriteria(new Criteria().orOperator(
                    Criteria.where("name").regex(pattern),
                    Criteria.where("legalPerson").regex(pattern),
                    Criteria.where("companyPrincipalPhone").regex(pattern)));
        }

        query.addCriteria(Criteria.where("delete").is(BaojinConstant.IS_NO_DELETE));
        query.with(new Sort(Sort.Direction.DESC, "createTime"));
        query.with(new Page(companySearchDto.getPage(), companySearchDto.getSize()));

        List<Company> companyList = mongoTemplate.find(query, Company.class);
        long count = mongoTemplate.count(query, Company.class);

        ModelList<Company> companyModelList = new ModelList<>(companyList, count);

        return companyModelList;
    }

    public List<String> getIdsByNameLike(String search) {
        Query query = new Query();
        if(search == null){
            search = "";
        }
        query.addCriteria(Criteria.where("name").regex(PatternUtil.fuzzyMatch(search)));
        query.fields().include("id");

        List<Company> deviceList = mongoTemplate.find(query, Company.class);
        return deviceList.stream().map(Company::getId).collect(Collectors.toList());
    }
}
